﻿





using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Spacebuilder.Common;
using Tunynet;
using Tunynet.Common;
using Tunynet.Common.Configuration;
using Tunynet.Mvc;
using Tunynet.UI;
using Tunynet.Utilities;
using System;
using Tunynet.FileStore;
using Spacebuilder.Common.Configuration;
using Tunynet.Email;
using Tunynet.Logging;

namespace Spacebuilder.Group.Controllers
{
    [Themed(PresentAreaKeysOfBuiltIn.GroupSpace, IsApplication = true)]
    [AnonymousBrowseCheck]
    [TitleFilter(IsAppendSiteName = true)]
    [GroupSpaceAuthorize(RequireManager = true)]
    public class GroupSpaceSettingsController : Controller
    {

        private IPageResourceManager pageResourceManager = DIContainer.ResolvePerHttpRequest<IPageResourceManager>();
        private CategoryService categoryService = new CategoryService();
        private GroupService groupService = new GroupService();
        private TagService tagService = new TagService(TenantTypeIds.Instance().Group());

        
        //这个多个地方用到
        /// <summary>
        /// 右侧导航菜单
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        public ActionResult _GroupSettingRightMenu(string spaceKey)
        {
            GroupEntity group = groupService.Get(spaceKey);
            PagingDataSet<GroupMemberApply> applys = groupService.GetGroupMemberApplies(group.GroupId, GroupMemberApplyStatus.Pending);
            long totalRecords = applys.TotalRecords;
            ViewData["totalRecords"] = totalRecords;
            return View(group);
        }

        /// <summary>
        /// 管理商户成员申请页
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ManageMemberApplies(string spaceKey, GroupMemberApplyStatus? applyStatus, int pageIndex = 1, int pageSize = 20)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return HttpNotFound();
            pageResourceManager.InsertTitlePart(group.GroupName);
            pageResourceManager.InsertTitlePart("管理商户成员申请页");
            
            //已修改
            PagingDataSet<GroupMemberApply> groupMemberApplies = groupService.GetGroupMemberApplies(group.GroupId, applyStatus, pageSize, pageIndex);
            ViewData["groupId"] = group.GroupId;
            TempData["GroupMenu"] = GroupMenu.ManageMember;
            ViewData["group"] = group;

            return View(groupMemberApplies);
        }

        /// <summary>
        /// 接受/拒绝商户加入申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult ApproveMemberApply(string spaceKey, IList<long> applyIds, bool isApproved)
        {
            
            
            long groupId = GroupIdToGroupKeyDictionary.GetGroupId(spaceKey);
            groupService.ApproveGroupMemberApply(applyIds, isApproved);
            return Json(new StatusMessageData(StatusMessageType.Success, "操作成功"));
        }


        /// <summary>
        /// 删除商户加入申请
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteMemberApply(string spaceKey, long id)
        {
            
            
            long groupId = GroupIdToGroupKeyDictionary.GetGroupId(spaceKey);
            groupService.DeleteGroupMemberApply(id);
            return Json(new StatusMessageData(StatusMessageType.Success, "操作成功"));
        }

        /// <summary>
        /// 管理商户成员页
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <param name="pageIndex"></param>
        /// <param name="currteGroupKey">子成员</param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ManageMembers(string spaceKey,string currteGroupKey="", int pageIndex = 1, int pageSize = 20)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return HttpNotFound();
            pageResourceManager.InsertTitlePart(group.GroupName);
            pageResourceManager.InsertTitlePart("管理商户成员页");

            ///子成员
            GroupEntity model = null;
            if (!string.IsNullOrEmpty(currteGroupKey))
            {
                model = groupService.Get(currteGroupKey);
            }
            PagingDataSet<GroupMember> groupMembers = null;
            if (model != null)
            {
                groupMembers = groupService.GetGroupMembers(model.GroupId, true, SortBy_GroupMember.DateCreated_Asc, pageSize, pageIndex);
            }
            else
            { 
               groupMembers = groupService.GetGroupMembers(group.GroupId, true, SortBy_GroupMember.DateCreated_Asc, pageSize, pageIndex);
            }
            
            ViewData["group"] = group;
            TempData["GroupMenu"] = GroupMenu.ManageMember;

            var gener = Request.QueryString.Get("gener");//获取性别
            var areaCode = Request.QueryString.Get("areaCode");//获取地区
            GenderType gendertype;
            List<GroupMember> list = groupMembers.ToList();
            PagingDataSet<GroupMember> newgroupMembers = new PagingDataSet<GroupMember>(list);
            if(!String.IsNullOrEmpty(gener))
            {
                gendertype = gener == "男" ? GenderType.Male : GenderType.FeMale;
                list.OrderBy(n => n.User.Profile.Gender == gendertype);
            }


            return View(newgroupMembers);
        }

        /// <summary>
        /// 子店铺成员
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <param name="pageIndex"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult ManageChildGroups(string spaceKey, int pageIndex = 1, int pageSize = 20)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return HttpNotFound();
            pageResourceManager.InsertTitlePart(group.GroupName);
            pageResourceManager.InsertTitlePart("管理子商户成员页");
            IEnumerable<GroupEntity> list = groupService.GetChildGroups(group.GroupId);

            ViewData["group"] = group;
            TempData["GroupMenu"] = GroupMenu.ManageMember;

            return View(list);
        }


        /// <summary>
        /// 创建更换商户管理员模式框
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>更换商户管理员</returns>
        [HttpGet]
        public ActionResult _ChangeGroupLimit(string spaceKey, string returnUrl)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);



            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return View(group);
        }

        /// <summary>
        /// 更换商户管理员
        /// </summary>
        /// <param name="group">编辑商户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _ChangeGroupLimit(string spaceKey)
        {
            string returnUrl = Request.QueryString.Get<string>(WebUtility.UrlDecode("returnUrl"));
            var userIds = Request.Form.Gets<long>("UserId", new List<long>());
            long userId = userIds.FirstOrDefault();
            #region 商户权限
            var ADDGROUP = Request.Form["ADDGROUP"];
            var DELGROUP = Request.Form["DELGROUP"];
            var ADDMEMBER = Request.Form["ADDMEMBER"];
            var DELMEMBER = Request.Form["DELMEMBER"];
            #endregion
            if (ADDGROUP.Contains("true"))
            {
                ADDGROUP = "true";
            }
            if (DELGROUP.Contains("true"))
            {
                DELGROUP = "true";
            }
            if (ADDMEMBER.Contains("true"))
            {
                ADDMEMBER = "true";
            }
            if (DELMEMBER.Contains("true"))
            {
                DELMEMBER = "true";
            }


            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);

           group.GroupRolls = ADDGROUP + "," + DELGROUP + "," + ADDMEMBER + "," + DELMEMBER;

            groupService.Update(userId, group);
            return Json(new StatusMessageData(StatusMessageType.Success, "更商户操作权限成功"));
        }

        /// <summary>
        /// 更改密码
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>更改密码</returns>
        [HttpGet]
        public ActionResult _ChangeGroupPwd(string spaceKey, string returnUrl)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);
            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return View(group);
        }

        /// <summary>
        /// 更换密码
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _ChangeGroupPwd(string spaceKey)
        {
            try
            {
                string returnUrl = Request.QueryString.Get<string>(WebUtility.UrlDecode("returnUrl"));
                ViewData["returnUrl"] = returnUrl;
                var password = Request.Form["password"];
                var newpassword = Request.Form["newpassword"];
                long UserId = 0;
                long.TryParse(Request.Form["UserId"], out UserId);
                var user = new UserService().GetFullUser(UserId);
                IMembershipService membershipService = DIContainer.Resolve<IMembershipService>();
                if (user != null)
                {
                    if (membershipService.ChangePassword(user.UserName, password, newpassword))
                    {
                        return Json(new StatusMessageData(StatusMessageType.Success, "更换密码成功"));
                    }
                    else
                    {
                        return Json(new StatusMessageData(StatusMessageType.Error, "原密码错误"));
                    }
                    
                }
                else
                {
                    return Json(new StatusMessageData(StatusMessageType.Error, "用户原始密码错误"));
                }
                
            }
            catch
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "更换失败"));
            }
        }

        /// <summary>
        /// 统计
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>统计</returns>
        [HttpGet]
        public ActionResult _ChangeGroupCount(string spaceKey, string returnUrl)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);
            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return View(group);
        }

        /// <summary>
        /// 转让会员
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>更换商户管理员</returns>
        [HttpGet]
        public ActionResult _ChangeGroupMember(string spaceKey, string returnUrl)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);



            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return View(group);
        }

        /// <summary>
        /// 转让会员
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>更换商户管理员</returns>
        [HttpPost]
        public ActionResult _ChangeGroupMember(string spaceKey)
        {
            var select2 = Request.Form["select2"];
            long group1=0;
            long.TryParse(Request.Form["group1"], out group1);
            if(select2==null || group1==0)
                return Json(new StatusMessageData(StatusMessageType.Error, "转让失败"));
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);
           var list = new GroupMemberRepository().GetAllMembersOfGroup(group.GroupId);
            if(list==null)
                 return Json(new StatusMessageData(StatusMessageType.Error, "转让失败"));
            foreach (var member in list)
            {
                if (select2.Contains(member.UserId.ToString()))
                {
                    member.GroupId = group1;
                    new GroupMemberRepository().Update(member);
                }
            }

            string returnUrl = Request.QueryString.Get<string>(WebUtility.UrlDecode("returnUrl"));
            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return Json(new StatusMessageData(StatusMessageType.Success, "转让成功"));
        }
        
        
        /// <summary>
        /// 创建更换商户管理员模式框
        /// </summary>
        /// <param name="groupId">商户Id</param>
        /// <param name="userId">商户管理员名称</param>
        /// <returns>更换商户管理员</returns>
        [HttpGet]
        public ActionResult _ChangeGroupOwner(string spaceKey, string returnUrl)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);
            
            
            
            ViewData["returnUrl"] = WebUtility.UrlDecode(returnUrl);
            return View(group);
        }

        
        
        /// <summary>
        /// 更换商户管理员
        /// </summary>
        /// <param name="group">编辑商户对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _ChangeGroupOwner(string spaceKey)
        {
            string returnUrl = Request.QueryString.Get<string>(WebUtility.UrlDecode("returnUrl"));
            
            var userIds = Request.Form.Gets<long>("UserId", new List<long>());
            long userId = userIds.FirstOrDefault();
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Content(string.Empty);
            if (userId == 0)
            {
                Tunynet.Utilities.WebUtility.SetStatusCodeForError(Response);
                ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Hint, "您没有选择商户管理员");
                ViewData["returnUrl"] = returnUrl;
                return View(group);
            }
            if (group.UserId == userId)
            {
                Tunynet.Utilities.WebUtility.SetStatusCodeForError(Response);
                ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Hint, "您没有更换商户管理员");
                ViewData["returnUrl"] = returnUrl;
                return View(group);
            }
            if (!new Authorizer().Group_SetManager(group))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "您没有更换商户管理员的权限"));
            }

            groupService.ChangeGroupOwner(group.GroupId, userId);
            return Json(new StatusMessageData(StatusMessageType.Success, "更换商户管理员操作成功"));
        }

        /// <summary>
        ///  设置/取消 商户管理员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult SetManager(string spaceKey, long userId, bool isManager)
        {
            StatusMessageData message = null;
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return HttpNotFound();

            if (!new Authorizer().Group_SetManager(group))
                return Json(new StatusMessageData(StatusMessageType.Error, "您没有设置管理员的权限"));

            bool result = groupService.SetManager(group.GroupId, userId, isManager);
            if (result)
            {
                message = new StatusMessageData(StatusMessageType.Success, "操作成功！");
            }
            else
            {
                message = new StatusMessageData(StatusMessageType.Error, "操作失败！");
            }
            return Json(message);
        }

        
        
        /// <summary>
        /// 批量移除商户成员
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult DeleteMember(string spaceKey, List<long> userIds)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return HttpNotFound();
            foreach (var userId in userIds)
            {
                if (!new Authorizer().Group_DeleteMember(group, userId))
                {
                    return Json(new StatusMessageData(StatusMessageType.Error, "您没有删除商户成员的权限"));
                }
            }
            //TODO:限制删除子店铺成员权限
            if (!string.IsNullOrEmpty(group.GroupRolls) && group.GroupRolls.Split(',')[4] == "true")
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "限制删除商户成员"));
            }

            
            
            
            groupService.DeleteGroupMember(group.GroupId, userIds);
            return Json(new StatusMessageData(StatusMessageType.Success, "操作成功"));
        }

        /// <summary>
        /// 删除商户logo
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _DeleteGroupLogo(string spaceKey)
        {
            GroupEntity group = groupService.Get(spaceKey);
            if (group == null)
                return Json(new StatusMessageData(StatusMessageType.Error, "没有该商户！"));
            IUser currentUser = UserContext.CurrentUser;
            if (currentUser == null)
                return Json(new StatusMessageData(StatusMessageType.Error, "您尚未登录！"));
            
            //已修改
            //这个功能属于编辑商户，在编辑商户已做权限验证，这边还需要做验证吗？
            
            groupService.DeleteLogo(group.GroupId);
            return Json(new StatusMessageData(StatusMessageType.Success, "删除商户Logo成功！"));
        }

        /// <summary>
        /// 编辑商户页
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpGet]
        public ActionResult EditGroup(string spaceKey)
        {
            GroupEntity group = groupService.Get(spaceKey);
            
            //已修改
            if (group == null)
                return HttpNotFound();
            pageResourceManager.InsertTitlePart(group.GroupName);
            pageResourceManager.InsertTitlePart("编辑商户");

            
            //编辑的时候需要显示已添加的标签
            IEnumerable<string> tags = group.TagNames;
            GroupEditModel groupEditModel = group.AsEditModel();
            ViewData["tags"] = tags;
            TempData["GroupMenu"] = GroupMenu.GroupSettings;

            return View(groupEditModel);
        }

        /// <summary>
        /// 编辑商户
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditGroup(string spaceKey, GroupEditModel groupEditModel)
        {
            IUser currentUser = UserContext.CurrentUser;
            if (currentUser == null)
                return Json(new StatusMessageData(StatusMessageType.Error, "您尚未登录！"));
            System.IO.Stream stream = null;
            HttpPostedFileBase groupLogo = Request.Files["GroupLogo"];

            if (groupLogo != null && !string.IsNullOrEmpty(groupLogo.FileName))
            {
                TenantLogoSettings tenantLogoSettings = TenantLogoSettings.GetRegisteredSettings(TenantTypeIds.Instance().Group());
                if (!tenantLogoSettings.ValidateFileLength(groupLogo.ContentLength))
                {
                    ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, string.Format("文件大小不允许超过{0}", Formatter.FormatFriendlyFileSize(tenantLogoSettings.MaxLogoLength * 1024)));
                    return View(groupEditModel);
                }

                LogoSettings logoSettings = DIContainer.Resolve<ILogoSettingsManager>().Get();
                if (!logoSettings.ValidateFileExtensions(groupLogo.FileName))
                {
                    ViewData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Error, "不支持的文件类型，仅支持" + logoSettings.AllowedFileExtensions);
                    return View(groupEditModel);
                }
                stream = groupLogo.InputStream;
                groupEditModel.Logo = groupLogo.FileName;
            }

            GroupEntity group = groupEditModel.AsGroupEntity();


            //设置分类
            if (groupEditModel.CategoryId > 0)
            {
                categoryService.ClearCategoriesFromItem(group.GroupId, 0, TenantTypeIds.Instance().Group());
                categoryService.AddItemsToCategory(new List<long>() { group.GroupId }, groupEditModel.CategoryId);
            }

            
            //已修改
            //设置标签
            string relatedTags = Request.Form.Get<string>("RelatedTags");
            if (!string.IsNullOrEmpty(relatedTags))
            {
                tagService.ClearTagsFromItem(group.GroupId, group.GroupId);
                tagService.AddTagsToItem(relatedTags, group.GroupId, group.GroupId);
            }
            if (stream != null)
            {
                groupService.UploadLogo(group.GroupId, stream);
            }

            groupService.Update(currentUser.UserId, group);
            TempData["StatusMessageData"] = new StatusMessageData(StatusMessageType.Success, "更新成功！");
            return Redirect(SiteUrls.Instance().EditGroup(group.GroupKey));
        }

        [HttpGet]
        public ActionResult _Menu_Manage(string spaceKey)
        {
            long groupId = GroupIdToGroupKeyDictionary.GetGroupId(spaceKey);
            GroupEntity group = groupService.Get(groupId);
            if (group == null)
                return Content(string.Empty);

            int currentNavigationId = RouteData.Values.Get<int>("CurrentNavigationId", 0);

            NavigationService navigationService = new NavigationService();
            Navigation navigation = navigationService.GetNavigation(PresentAreaKeysOfBuiltIn.GroupSpace, currentNavigationId, group.GroupId);

            IEnumerable<Navigation> navigations = new List<Navigation>();
            if (navigation != null)
            {
                if (navigation.Depth >= 1 && navigation.Parent != null)
                {
                    navigations = navigation.Parent.Children;
                }
                else if (navigation.Depth == 0)
                {
                    navigations = navigation.Children;
                }
            }

            ViewData["MemberApplyCount"] = groupService.GetMemberApplyCount(group.GroupId);

            return View(navigations);
        }


        #region 完善个人资料向导
        #region private items

        private UserProfileService userProfileService=new UserProfileService();
        private IStoreProvider storeProvider = DIContainer.Resolve<IStoreProvider>();
        private IUserService userService = DIContainer.Resolve<IUserService>();
        private UserProfileSettings userProfileSettings = DIContainer.Resolve<IUserProfileSettingsManager>().GetUserProfileSettings();
        private UserBlockService userBlockService = new UserBlockService();
        private PrivacyService privacyService = new PrivacyService();
        private IMembershipService membershipService = DIContainer.Resolve<IMembershipService>();
        private IAuthenticationService authenticationService = DIContainer.ResolvePerHttpRequest<IAuthenticationService>();
        private IPrivacySettingsManager privacySettingsManager = DIContainer.Resolve<IPrivacySettingsManager>();
        IPointSettingsManager pointSettingsManger = DIContainer.Resolve<IPointSettingsManager>();
        private IUserSettingsManager userSettingsManager = DIContainer.Resolve<IUserSettingsManager>();
        private AccountBindingService accountBindingService = new AccountBindingService();
        #endregion private items
        /// <summary>
        /// 上传头像向导
        /// </summary>
        /// <returns></returns>
        public ActionResult UserProfileGuideAvatar(string spaceKey,long userid)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            User user = userService.GetFullUser(userid);
            //if (UserContext.CurrentUser == null || UserContext.CurrentUser.UserId != user.UserId)
            //{ return Json(new StatusMessageData(StatusMessageType.Error, "你没有权限！")); }

            pageResourceManager.InsertTitlePart("完善个人资料向导");
            pageResourceManager.InsertTitlePart("上传头像");
            return View(user);
        }

        /// <summary>
        ///填写个人资料向导 
        /// </summary>
        /// <returns></returns>
        public ActionResult UserProfileGuideDetail(string spaceKey, long userid)
        {
              
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            User user = userService.GetFullUser(userid);
            //if (UserContext.CurrentUser == null || UserContext.CurrentUser.UserId != user.UserId)
            //{ return RedirectToAction("SpaceHome"); }

            if (user == null)
            { return HttpNotFound(); }
            ViewData["userProfile"] = userProfileService.Get(user.UserId) == null ? new UserProfile() : userProfileService.Get(user.UserId);
            ViewData["user"] = user;
            pageResourceManager.InsertTitlePart("完善个人资料向导");
            pageResourceManager.InsertTitlePart("填写个人资料");

            #region 年份

            IList<int> startDateList = new List<int>();
            int nowYear = DateTime.Now.Year;
            for (int j = 0; j < 50; j++)
            {
                startDateList.Add(nowYear - j);
            }
            ViewData["StartYear"] = new SelectList(startDateList.Select(n => new { text = n.ToString(), value = n.ToString() }), "value", "text");

            IDictionary<string, string> endDateDict = new Dictionary<string, string>();

            endDateDict["至今"] = DateTime.Now.Year.ToString();
            for (int k = 1; k <= 50; k++)
            {
                endDateDict[(nowYear - k).ToString()] = (nowYear - k).ToString();
            }
            ViewData["EndDate"] = new SelectList(endDateDict.Select(n => new { text = n.Key, value = n.Value }), "value", "text");

            #endregion

            return View();
        }

        /// <summary>
        /// 个人标签向导
        /// </summary>
        /// <returns></returns>
        public ActionResult UserProfileGuideTag(string spaceKey,long userid)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            User user = userService.GetFullUser(userid);
            //if (UserContext.CurrentUser == null || UserContext.CurrentUser.UserId != user.UserId)
            //{ return RedirectToAction("SpaceHome"); }

            pageResourceManager.InsertTitlePart("完善个人资料向导");
            pageResourceManager.InsertTitlePart("填写个人标签");
            ViewData["user"] = user;
            return View();
        }

        /// <summary>
        /// 看看感兴趣的人向导
        /// </summary>
        /// <returns></returns>
        public ActionResult UserProfileGuideInterested(string spaceKey,long userid)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            var group = groupService.Get(spaceKey);
            User user = userService.GetFullUser(userid);
            //if (UserContext.CurrentUser == null || UserContext.CurrentUser.UserId != user.UserId)
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            ViewData["user"] = user;
            pageResourceManager.InsertTitlePart("完善个人资料向导");
            pageResourceManager.InsertTitlePart("看看感兴趣的人");

            return View();
        }

        /// <summary>
        /// 个人标签向导局部页
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        /// <returns></returns>
        public ActionResult _EditUserProfileTag(long userid=0)
        {
            User user = userService.GetFullUser(userid);
            ViewData["user"] = user;
            return View();
        }

        /// <summary>
        /// 个人资料向导局部页
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        /// <returns></returns>
        public ActionResult _EditUserProfileDetail(string spaceKey,long  userid)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            User user = userService.GetFullUser(userid);
            if (user == null) { return HttpNotFound(); }

            UserProfile profile = userProfileService.Get(user.UserId);
            UserProfileEditModel editModel = new UserProfileEditModel(profile, user);

            int minYear = 1919;
            int i = DateTime.Now.Year - minYear;
            IList<SelectListItem> years = new List<SelectListItem>();

            while (i >= 0)
            {
                DateTime dt = DateTime.Now.AddYears(-i);
                years.Add(new SelectListItem() { Text = string.Format("{0}年({1})", ChineseCalendarHelper.GetStemBranch(dt), dt.Year), Value = dt.Year.ToString() });
                i--;
            }

            ViewData["Year"] = years;
            ViewData["minYear"] = minYear;

            ViewData["UserName"] = user.UserName;
            ViewData["statusMessageData"] = TempData["MessageData"];
            #region 隐私设置

            List<SelectListItem> selectListItems = new List<SelectListItem> 
            {
                new SelectListItem{ Text = "所有人可见", Value = PrivacyStatus.Public.ToString()},
                new SelectListItem{ Text = "我收藏的人可见", Value = PrivacyStatus.Part.ToString()},
                new SelectListItem{ Text = "仅自己可见", Value = PrivacyStatus.Private.ToString()}
            };


            Dictionary<string, PrivacyStatus> userPrivacyItems = GetUserPrivacySetting(user.UserId);

            ViewData["PrivacyEmail"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Email()]);
            ViewData["PrivacyMobile"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Mobile()]);
            ViewData["PrivacyBirthday"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Birthday()]);
            ViewData["PrivacyQQ"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().QQ()]);
            ViewData["PrivacyMSN"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Msn()]);
            ViewData["PrivacyTrueName"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().TrueName()]);

            #endregion

            return View(editModel);
        }

        /// <summary>
        ///上传头像向导局部页 
        /// </summary>
        /// <returns></returns>
        public ActionResult _EditUserProfileAvatar(string spaceKey, long userid)
        {
            User user = userService.GetFullUser(userid);
            return View(user);
        }

        /// <summary>
        /// 完成向导局部页
        /// </summary>
        /// <returns></returns>
        public ActionResult _CompleteGuide(string spaceKey,long userid)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            return View();
        }

        /// <summary>
        /// 下次登录是否需要向导
        /// </summary>
        /// <param name="spaceKey">空间标识</param>
        /// <param name="isNeedGuide">true为不需要</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _CompleteGuide(string spaceKey, bool isNeedGuide)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            User user = userService.GetFullUser(spaceKey);

            user.Profile.IsNeedGuide = isNeedGuide;
            userProfileService.Update(user.Profile);
            return Json(new StatusMessageData(StatusMessageType.Success, "设置成功！"));
        }

        #endregion

        #region 上传头像

        /// <summary>
        /// 取消头像裁剪
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        public JsonResult _CancelAvatar(string spaceKey,long userid)
        {
            User user = userService.GetFullUser(userid);
            long userId = UserIdToUserNameDictionary.GetUserId(user.UserName);
            new UserService().DeleteAvatar(userId);
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 头像裁剪
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        /// <param name="srcWidth">宽</param>
        /// <param name="srcHeight">高</param>
        /// <param name="srcX">左上角X坐标</param>
        /// <param name="srcY">左上角上角Y坐标</param>
        public JsonResult _CropAvatar(string spaceKey, float srcWidth, float srcHeight, float srcX, float srcY, long userid)
        {
            UserService userService = new UserService();

            User user = userService.GetFullUser(userid);
            long userId = UserIdToUserNameDictionary.GetUserId(user.UserName);
            userService.CropAvatar(userId, srcWidth, srcHeight, srcX, srcY);
            IStoreFile iStoreFile = userService.GetAvatar(userId, AvatarSizeType.Original);
            if (iStoreFile != null)
            {
                storeProvider.DeleteFile(iStoreFile.RelativePath, iStoreFile.Name);
            }
            return Json(new { success = true }, JsonRequestBehavior.AllowGet);
        }

        /// <summary>
        /// 头像局部视图异步加载
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        public ActionResult _EditAvatarAsyn(string spaceKey,long userid=0)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            if (userid == 0)
            {
                long.TryParse(Request.QueryString["userid"], out userid);
            }
            User user = userService.GetFullUser(userid);
            if (user == null)
                return new EmptyResult();

            IStoreFile iStoreFile = new UserService().GetAvatar(user.UserId, AvatarSizeType.Original);
            if (!user.HasAvatar && iStoreFile != null)
            {
                string originalImageUrl = SiteUrls.Instance().UserAvatarUrl(user, AvatarSizeType.Original, false);
                string idString = user.UserId.ToString().PadLeft(15, '0');
                string idPart = storeProvider.JoinDirectory(idString.Substring(0, 5), idString.Substring(5, 5), idString.Substring(10, 5));
                idPart = idPart.Replace("\\", "/");
                originalImageUrl = originalImageUrl.Substring(0, originalImageUrl.LastIndexOf('/') + 1)
                                   + idPart + "/" + user.UserId + "_" + AvatarSizeType.Original.ToString()
                                   + originalImageUrl.Substring(originalImageUrl.LastIndexOf('.'));
                ViewData["originalImageUrl"] = originalImageUrl;
            }
            else if (iStoreFile != null)
            {
                ViewData["originalImageUrl"] = SiteUrls.Instance().UserAvatarUrl(user, AvatarSizeType.Original, false);
            }

            ViewData["bigImageUrl"] = SiteUrls.Instance().UserAvatarUrl(user, AvatarSizeType.Big, false);
            ViewData["SmallImageUrl"] = SiteUrls.Instance().UserAvatarUrl(user, AvatarSizeType.Small, false);

            return View(user);
        }

        /// <summary>
        /// 编辑头像显示页面
        /// </summary>
        /// <param name="spaceKey">空间标示</param>
        public ActionResult EditAvatar(string spaceKey)
        {
            //if (!string.IsNullOrEmpty(GroupMemberAuthorizeAttribute.Ismember(spaceKey)))
            //{
            //    return RedirectToAction("SpaceHome");
            //}
            pageResourceManager.InsertTitlePart("上传头像");

            //OK
            return View();
        }

        #endregion 上传头像

        #region 基本资料

        /// <summary>
        /// 用户图片
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        public ActionResult UserAlbums(string spaceKey)
        {
            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();
            pageResourceManager.InsertTitlePart("上传图片");
            ViewData["UserAlbumrs"] = user.Useralbumrs;


            //OK
            return View(new UserAlbumr() { UserId = user.UserId });
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpPost]
        [ValidateInput(false)]
        public ActionResult UserAlbums(UserAlbumr useralbumr)
        {
            User user = new User();
            if (!string.IsNullOrEmpty(useralbumr.FeaturedImageAttachmentId))
            {
                string[] str;
                if (useralbumr.FeaturedImageAttachmentId.Contains(','))
                {
                    str = useralbumr.FeaturedImageAttachmentId.Split(',');
                }
                else
                {
                    str = new string[] { useralbumr.FeaturedImageAttachmentId };
                }
                for (int j = 0; j < str.Length; j++)
                {
                    int i = 0;
                    int.TryParse(str[i], out i);
                    AttachmentService<Attachment> attachmentService = new AttachmentService<Attachment>(TenantTypeIds.Instance().UserAlbumr());
                    Attachment attachment = attachmentService.Get(i);
                    if (attachment != null)
                    {
                        useralbumr.FeaturedImage = attachment.GetRelativePath() + "\\" + attachment.FileName;
                    }
                    else
                    {
                        useralbumr.FeaturedImageAttachmentId = "0";
                    }
                    UserAlbumrRepository resp = new UserAlbumrRepository();
                    useralbumr.CreateTime = DateTime.Now;
                    useralbumr.DisplayOrder = 0;
                    resp.Insert(useralbumr);
                    user = userService.GetFullUser(useralbumr.UserId);
                }
            }

            return RedirectToAction("UserAlbums", new { user.UserName });
        }

        /// <summary>
        /// 编辑用户基本情况
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        public ActionResult _EditBaseCaseDetail(string spaceKey,long userid)
        {
            User user = userService.GetFullUser(userid);
            if (user == null)
                return HttpNotFound();

            pageResourceManager.InsertTitlePart("基本情况");

            UserProfile profile = userProfileService.Get(user.UserId);
            BaseCase basecase = new BaseCaseRepository().BaseCaseOfUser(user.UserId);
            EachRequest eachrequest = new EachRequestRepository().EachCaseOfUser(user.UserId);
            UserProfileEditModel editModel = new UserProfileEditModel(profile, user, basecase, eachrequest);

            int minYear = 1919;
            int i = DateTime.Now.Year - minYear;
            IList<SelectListItem> years = new List<SelectListItem>();

            while (i >= 0)
            {
                DateTime dt = DateTime.Now.AddYears(-i);
                years.Add(new SelectListItem() { Text = string.Format("{0}年({1})", ChineseCalendarHelper.GetStemBranch(dt), dt.Year), Value = dt.Year.ToString() });
                i--;
            }

            ViewData["Year"] = years;
            ViewData["minYear"] = minYear;

            ViewData["UserName"] = user.UserName;
            //ViewData["statusMessageData"] = TempData["MessageData"];
            #region 隐私设置

            List<SelectListItem> selectListItems = new List<SelectListItem> 
            {
                new SelectListItem{ Text = "所有人可见", Value = PrivacyStatus.Public.ToString()},
                new SelectListItem{ Text = "我收藏的人可见", Value = PrivacyStatus.Part.ToString()},
                new SelectListItem{ Text = "仅自己可见", Value = PrivacyStatus.Private.ToString()}
            };


            Dictionary<string, PrivacyStatus> userPrivacyItems = GetUserPrivacySetting(user.UserId);

            ViewData["PrivacyEmail"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Email()]);
            ViewData["PrivacyMobile"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Mobile()]);
            ViewData["PrivacyBirthday"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Birthday()]);
            ViewData["PrivacyQQ"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().QQ()]);
            ViewData["PrivacyMSN"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Msn()]);
            ViewData["PrivacyTrueName"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().TrueName()]);

            #endregion

            return View(editModel);
        }
        /// <summary>
        /// 基本情况提交
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditBaseCase(UserProfileEditModel model)
        {
            User user = userService.GetFullUser(model.UserId);
            if (user == null)
                return HttpNotFound();
            BaseCaseRepository reps = new BaseCaseRepository();
            #region 赋值
            user.Basecase.BlindDate = model.BlindDate;
            user.Basecase.BloodType = model.BloodType;
            user.Basecase.Culinary = model.Culinary;
            user.Basecase.Drinking = model.Drinking;
            user.Basecase.FamilyMembers = model.FamilyMembers;
            user.Basecase.Figure = model.Figure;
            user.Basecase.Height = model.Height;
            user.Basecase.Housework = model.Housework;
            user.Basecase.License = model.License;
            user.Basecase.LikeMovie = model.LikeMovie;
            user.Basecase.LiveParents = model.LiveParents;
            user.Basecase.MaritalStatus = model.MaritalStatus;
            user.Basecase.MasterLanguage = model.MasterLanguage;
            user.Basecase.Nation = model.Nation;
            user.Basecase.PurchaseCar = model.PurchaseCar;
            user.Basecase.Salary = model.Salary;
            user.Basecase.Smoking = model.Smoking;
            user.Basecase.SonInLaw = model.SonInLaw;
            user.Basecase.TheHousing = model.TheHousing;
            user.Basecase.UserId = model.UserId;
            user.Basecase.Weight = model.Weight;
            user.Basecase.WhenMarried = model.WhenMarried;
            user.Basecase.Zodiac = model.Zodiac;
            #endregion
            if (user.Basecase.Id > 0)
            {
                reps.Update(user.Basecase);
            }
            else
            {
                reps.Insert(user.Basecase);
            }
            return Json(new StatusMessageData(StatusMessageType.Success, "更新用户成功"));
        }

        /// <summary>
        /// 编辑用户相亲要求
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        public ActionResult _EditEachRequestDetail(string spaceKey, long userid)
        {
            User user = userService.GetFullUser(userid);
            if (user == null)
                return HttpNotFound();

            pageResourceManager.InsertTitlePart("基本要求");

            UserProfile profile = userProfileService.Get(user.UserId);
            UserProfileEditModel editModel = new UserProfileEditModel(profile, user);

            int minYear = 1919;
            int i = DateTime.Now.Year - minYear;
            IList<SelectListItem> years = new List<SelectListItem>();

            while (i >= 0)
            {
                DateTime dt = DateTime.Now.AddYears(-i);
                years.Add(new SelectListItem() { Text = string.Format("{0}年({1})", ChineseCalendarHelper.GetStemBranch(dt), dt.Year), Value = dt.Year.ToString() });
                i--;
            }

            ViewData["Year"] = years;
            ViewData["minYear"] = minYear;

            ViewData["UserName"] = user.UserName;
            //ViewData["statusMessageData"] = TempData["MessageData"];
            #region 隐私设置

            List<SelectListItem> selectListItems = new List<SelectListItem> 
            {
                new SelectListItem{ Text = "所有人可见", Value = PrivacyStatus.Public.ToString()},
                new SelectListItem{ Text = "我收藏的人可见", Value = PrivacyStatus.Part.ToString()},
                new SelectListItem{ Text = "仅自己可见", Value = PrivacyStatus.Private.ToString()}
            };


            Dictionary<string, PrivacyStatus> userPrivacyItems = GetUserPrivacySetting(user.UserId);

            ViewData["PrivacyEmail"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Email()]);
            ViewData["PrivacyMobile"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Mobile()]);
            ViewData["PrivacyBirthday"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Birthday()]);
            ViewData["PrivacyQQ"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().QQ()]);
            ViewData["PrivacyMSN"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Msn()]);
            ViewData["PrivacyTrueName"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().TrueName()]);

            #endregion

            return View(editModel);
        }

        /// <summary>
        /// 对象要求
        /// </summary>
        /// <param name="spaceKey"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult EditEachRequest(UserProfileEditModel model)
        {
            User user = userService.GetFullUser(model.UserId);
            if (user == null)
                return HttpNotFound();
            EachRequestRepository reps = new EachRequestRepository();
            #region 赋值
            user.Eachrequest.OtherCharacter = model.OtherCharacter;
            user.Eachrequest.OtherEducation = model.OtherEducation;
            user.Eachrequest.OtherHeight = model.OtherHeight;
            user.Eachrequest.OtherHousingSituation = model.OtherHousingSituation;
            user.Eachrequest.OtherMaritalStatus = model.OtherMaritalStatus;
            user.Eachrequest.OtherOccupation = model.OtherOccupation;
            user.Eachrequest.OtherPlaceResidence = model.OtherPlaceResidence;
            user.Eachrequest.OtherPlaceWork = model.OtherPlaceWork;
            user.Eachrequest.OtherRegistered = model.OtherRegistered;
            user.Eachrequest.UserId = model.UserId;

            #endregion
            if (user.Eachrequest.Id > 0)
            {
                reps.Update(user.Eachrequest);
            }
            else
            {
                reps.Insert(user.Eachrequest);
            }
            return Json(new StatusMessageData(StatusMessageType.Success, "更新用户成功"));
        }

        /// <summary>
        /// 编辑用户资料-基本资料页面
        /// </summary>
        [HttpGet]
        public ActionResult EditUserProfile(string spaceKey,long userid)
        {
            User user = userService.GetFullUser(userid);
            if (user == null)
                return HttpNotFound();

            pageResourceManager.InsertTitlePart("基本资料");

            UserProfile profile = userProfileService.Get(user.UserId);
            UserProfileEditModel editModel = new UserProfileEditModel(profile, user);

            int minYear = 1919;
            int i = DateTime.Now.Year - minYear;
            IList<SelectListItem> years = new List<SelectListItem>();

            while (i >= 0)
            {
                DateTime dt = DateTime.Now.AddYears(-i);
                years.Add(new SelectListItem() { Text = string.Format("{0}年({1})", ChineseCalendarHelper.GetStemBranch(dt), dt.Year), Value = dt.Year.ToString() });
                i--;
            }

            ViewData["Year"] = years;
            ViewData["minYear"] = minYear;

            ViewData["UserName"] = user.UserName;
            //ViewData["statusMessageData"] = TempData["MessageData"];
            #region 隐私设置

            List<SelectListItem> selectListItems = new List<SelectListItem> 
            {
                new SelectListItem{ Text = "所有人可见", Value = PrivacyStatus.Public.ToString()},
                new SelectListItem{ Text = "我收藏的人可见", Value = PrivacyStatus.Part.ToString()},
                new SelectListItem{ Text = "仅自己可见", Value = PrivacyStatus.Private.ToString()}
            };


            Dictionary<string, PrivacyStatus> userPrivacyItems = GetUserPrivacySetting(user.UserId);

            ViewData["PrivacyEmail"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Email()]);
            ViewData["PrivacyMobile"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Mobile()]);
            ViewData["PrivacyBirthday"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Birthday()]);
            ViewData["PrivacyQQ"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().QQ()]);
            ViewData["PrivacyMSN"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().Msn()]);
            ViewData["PrivacyTrueName"] = new SelectList(selectListItems, "Value", "Text", userPrivacyItems[PrivacyItemKeys.Instance().TrueName()]);

            #endregion

            return View(editModel);
        }

        /// <summary>
        /// 更新基本资料 表单提交
        /// </summary>
        /// <param name="spaceKey">spaceKey</param>
        /// <param name="model">用于表单提交的实体</param>
        [HttpPost]
        public JsonResult EditUserProfile(string spaceKey, UserProfileEditModel model,long userid)
        {
            string errorMessage = null;
            if (ModelState.HasBannedWord(out errorMessage))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, errorMessage));
            }

            User oldUser = userService.GetFullUser(userid);
            string oldemail = oldUser.AccountEmail;

            UserProfile userProfile = model.AsUserProfile(oldUser.UserId);
            if (userProfileService.Get(oldUser.UserId) != null)
                userProfileService.Update(userProfile);
            else
                userProfileService.Create(userProfile);

            User user = model.AsUser(oldUser.UserId);

            if (oldemail.Equals(model.AccountEmail) || Utility.ValidateEmail(model.AccountEmail, out errorMessage))
            {
                user.AccountEmail = model.AccountEmail;

                if (oldemail != model.AccountEmail)
                    user.IsEmailVerified = false;

                IMembershipService iMembershipService = DIContainer.Resolve<IMembershipService>();

                //更新用户名
                if (!string.IsNullOrEmpty(model.UserName))
                    user.UserName = model.UserName;

                iMembershipService.UpdateUser(user);
            }

            #region 处理隐私设置

            Dictionary<string, IEnumerable<UserPrivacySpecifyObject>> userPrivacySpecifyObject = new Dictionary<string, IEnumerable<UserPrivacySpecifyObject>>();
            if (model.PrivacyBirthday == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().Birthday(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            if (model.PrivacyEmail == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().Email(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            if (model.PrivacyMobile == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().Mobile(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            if (model.PrivacyMSN == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().Msn(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            if (model.PrivacyQQ == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().QQ(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });

            Dictionary<string, PrivacyStatus> userSettings = new Dictionary<string, PrivacyStatus>();
            userSettings.Add(PrivacyItemKeys.Instance().Birthday(), model.PrivacyBirthday);
            userSettings.Add(PrivacyItemKeys.Instance().Email(), model.PrivacyEmail);
            userSettings.Add(PrivacyItemKeys.Instance().Mobile(), model.PrivacyMobile);
            userSettings.Add(PrivacyItemKeys.Instance().Msn(), model.PrivacyMSN);
            userSettings.Add(PrivacyItemKeys.Instance().QQ(), model.PrivacyQQ);

            privacyService.UpdateUserPrivacySettings(user.UserId, userSettings, userPrivacySpecifyObject);

            #endregion

            if (!string.IsNullOrEmpty(errorMessage))
                return Json(new StatusMessageData(StatusMessageType.Error, "更新邮件失败"));

            return Json(new StatusMessageData(StatusMessageType.Success, "更新用户成功"));

        }

        /// <summary>
        /// 编辑用户资料-基本资料页面
        /// </summary>
        [HttpGet]
        public ActionResult SendAsyn(string spaceKey)
        {
            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();

            bool sendStatus = false;
            try
            {
                System.Net.Mail.MailMessage mailMessage = EmailBuilder.Instance().RegisterValidateEmail(user);
                EmailService emailService = new EmailService();
                sendStatus = emailService.SendAsyn(mailMessage);
            }
            catch (Exception e)
            {
                ILogger logger = LoggerFactory.GetLogger();
                logger.Error(e, "异步发送激活邮件时报错");
            }

            if (sendStatus)
            {
                TempData["SendEmailSucceedViewModel"] = SendEmailSucceedViewModelFactory.GetRegisterSendEmailSucceedViewModel(user.AccountEmail);
                return Redirect(SiteUrls.Instance().SendEmailSucceed());
            }
            TempData["SendEmailStatus"] = false;
            return RedirectToAction("EditUserProfile", new { spaceKey = spaceKey });
        }

        /// <summary>
        /// 修改用户账户邮箱
        /// </summary>
        [HttpGet]
        public ActionResult _EditUserAccountEmail(string spaceKey)
        {

            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();
            ViewData["userId"] = user.UserId;
            ViewData["email"] = Request.QueryString["email"];
            return View();
        }

        /// <summary>
        /// 修改用户账户邮箱表单
        /// </summary>
        [HttpPost]
        public ActionResult EditUserAccountEmail(string spaceKey)
        {
            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();

            string accountEmail = Request.Form["_accountEmail"];

            if (string.IsNullOrEmpty(accountEmail))
            {
                WebUtility.SetStatusCodeForError(Response);
                ViewData["statusMessageData"] = new StatusMessageData(StatusMessageType.Error, "对不起，邮箱不能为空");
                ViewData["email"] = accountEmail;
                return View("_EditUserAccountEmail");
            }
            string errmessage = "";
            bool isValid = Utility.ValidateEmail(accountEmail, out errmessage);
            if (!isValid)
            {
                WebUtility.SetStatusCodeForError(Response);
                ViewData["statusMessageData"] = new StatusMessageData(StatusMessageType.Error, WebUtility.HtmlDecode(errmessage));
                ViewData["email"] = accountEmail;
                return View("_EditUserAccountEmail");
            }

            user.AccountEmail = accountEmail;
            IMembershipService iMembershipService = DIContainer.Resolve<IMembershipService>();
            iMembershipService.UpdateUser(user);

            return RedirectToAction("EditUserProfile", new { spaceKey = spaceKey });
        }

        #endregion 基本资料

        #region 教育经历

        /// <summary>
        /// 编辑用户资料-教育经历页面
        /// </summary>
        [HttpGet]
        public ActionResult EditUserEducation(string spaceKey)
        {

            Dictionary<string, PrivacyStatus> userPrivacySettings = GetUserPrivacySetting(UserIdToUserNameDictionary.GetUserId(spaceKey));
            PrivacyStatus privacyStatus = userPrivacySettings[PrivacyItemKeys.Instance().EducationExperience()];
            Dictionary<PrivacyStatus, string> privacyStatusNames = new Dictionary<PrivacyStatus, string>
            {
                {PrivacyStatus.Public, "所有人可见"},
                {PrivacyStatus.Part, "我收藏的人可见"},
                {PrivacyStatus.Private, "仅自己可见"}
            };
            ViewData["EditUserEducationPrivacy"] = new KeyValuePair<PrivacyStatus, string>(privacyStatus, privacyStatusNames[privacyStatus]);
            pageResourceManager.InsertTitlePart("教育经历");
            return View();
        }

        /// <summary>
        /// 编辑教育经历页面
        /// </summary>
        [HttpGet]
        public ActionResult _UserEducations(string spaceKey)
        {
            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            IEnumerable<EducationExperience> userExperiences = userProfileService.GetEducationExperiences(userId);
            return View(userExperiences);
        }

        /// <summary>
        /// 编辑教育经历页面
        /// </summary>
        public ActionResult _EditUserEducationInfo(string spaceKey, long? educationId)
        {
            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();
            ViewData["userProfile"] = userProfileService.Get(user.UserId);

            EducationExperienceEditModel editModel = new EducationExperienceEditModel();

            IList<int> startDateList = new List<int>();
            int nowYear = DateTime.Now.Year;
            for (int i = 0; i < 50; i++)
            {
                startDateList.Add(nowYear - i);
            }
            ViewData["StareYear"] = new SelectList(startDateList.Select(n => new { text = n.ToString(), value = n.ToString() }), "value", "text");

            if (educationId.HasValue && educationId > 0)
            {
                EducationExperience edu = userProfileService.GetEducationExperience(educationId.Value, user.UserId);
                if (edu != null)
                    editModel = edu.AsEditModel();
            }

            return View(editModel);
        }

        /// <summary>
        /// 编辑 教育经历
        /// </summary>
        /// <param name="model">用于表单提交的实体</param>
        [HttpPost]
        public JsonResult UpdateEducation(string spaceKey, EducationExperienceEditModel model)
        {
            string message = string.Empty;
            if (ModelState.HasBannedWord(out message))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, message));
            }

            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);

            EducationExperience education = model.AsEducationExperience(userId);
            userProfileService.UpdateEducationExperience(education);

            if (education.Id > 0)
                return Json(new StatusMessageData(StatusMessageType.Success, "更新教育经历成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "更新教育经历失败!"));
        }

        /// <summary>
        /// 添加 教育经历表单提交
        /// </summary>
        /// <param name="model">用于表单提交的实体</param>
        [HttpPost]
        public JsonResult CreateEducation(string spaceKey, EducationExperienceEditModel model,long userid)
        {
            string message = string.Empty;
            if (ModelState.HasBannedWord(out message))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, message));
            }

            long userId = userid; //UserIdToUserNameDictionary.GetUserId(spaceKey);

            EducationExperience education = model.AsEducationExperience(userId);
            bool result = userProfileService.CreateEducationExperience(education);
            if (result)
                return Json(new StatusMessageData(StatusMessageType.Success, "创建教育经历成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "创建教育经历失败!"));
        }

        /// <summary>
        /// 删除教育经历
        /// </summary>
        /// <param name="educationId">教育经历ID</param>
        [HttpPost]
        public JsonResult DeleteUserEducation(string spaceKey, long educationId)
        {
            userProfileService.DeleteEducationExperience(educationId);
            if (educationId > 0)
                return Json(new StatusMessageData(StatusMessageType.Success, "删除成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "删除失败!"));
        }



        /// <summary>
        /// 更新用户教育隐私设置
        /// </summary>
        /// <param name="spaceKey">空间名</param>
        /// <param name="EditUserEducationPrivacy">教育信息隐私设置</param>
        /// <returns>用户教育隐私设置结果</returns>
        [HttpPost]
        public ActionResult EditUserEducationPrivacySetting(string spaceKey, PrivacyStatus EditUserEducationPrivacy)
        {
            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            Dictionary<string, PrivacyStatus> userSetting = new Dictionary<string, PrivacyStatus>();
            userSetting.Add(PrivacyItemKeys.Instance().EducationExperience(), EditUserEducationPrivacy);
            Dictionary<string, IEnumerable<UserPrivacySpecifyObject>> userPrivacySpecifyObject = new Dictionary<string, IEnumerable<UserPrivacySpecifyObject>>();
            if (EditUserEducationPrivacy == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().EducationExperience(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            privacyService.UpdateUserPrivacySettings(userId, userSetting, userPrivacySpecifyObject);

            return Json(new StatusMessageData(StatusMessageType.Success, "更新教育隐私设置成功"));
        }


        #endregion 教育经历

        #region 工作经历

        /// <summary>
        /// 编辑用户资料-工作经历页面
        /// </summary>
        [HttpGet]
        public ActionResult EditUserWork(string spaceKey)
        {
            Dictionary<string, PrivacyStatus> userPrivacySettings = GetUserPrivacySetting(UserIdToUserNameDictionary.GetUserId(spaceKey));
            PrivacyStatus privacyStatus = userPrivacySettings[PrivacyItemKeys.Instance().WorkExperience()];
            Dictionary<PrivacyStatus, string> privacyStatusNames = new Dictionary<PrivacyStatus, string>
            {
                {PrivacyStatus.Public, "所有人可见"},
                {PrivacyStatus.Part, "我收藏的人可见"},
                {PrivacyStatus.Private, "仅自己可见"}
            };
            ViewData["EditUserWorkPrivacy"] = new KeyValuePair<PrivacyStatus, string>(privacyStatus, privacyStatusNames[privacyStatus]);
            pageResourceManager.InsertTitlePart("工作经历");

            return View();
        }

        /// <summary>
        /// 更新用户教育隐私设置
        /// </summary>
        /// <param name="spaceKey">空间名</param>
        /// <param name="EditUserWorkPrivacy">教育信息隐私设置</param>
        /// <returns>用户教育隐私设置结果</returns>
        [HttpPost]
        public ActionResult EditUserWorkPrivacyPrivacySetting(string spaceKey, PrivacyStatus EditUserWorkPrivacy)
        {
            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            Dictionary<string, PrivacyStatus> userSetting = new Dictionary<string, PrivacyStatus>();
            userSetting.Add(PrivacyItemKeys.Instance().WorkExperience(), EditUserWorkPrivacy);
            Dictionary<string, IEnumerable<UserPrivacySpecifyObject>> userPrivacySpecifyObject = new Dictionary<string, IEnumerable<UserPrivacySpecifyObject>>();
            if (EditUserWorkPrivacy == PrivacyStatus.Part)
                userPrivacySpecifyObject.Add(PrivacyItemKeys.Instance().EducationExperience(), new List<UserPrivacySpecifyObject> { GetUserPrivacySpecifyObject_AllGroup() });
            privacyService.UpdateUserPrivacySettings(userId, userSetting, userPrivacySpecifyObject);

            return Json(new StatusMessageData(StatusMessageType.Success, "更新工作经历隐私设置成功"));
        }

        /// <summary>
        /// 工作经历页面
        /// </summary>
        [HttpGet]
        public ActionResult _UserWorks(string spaceKey)
        {
            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            IEnumerable<WorkExperience> workExperiences = userProfileService.GetWorkExperiences(userId);
            return View(workExperiences);
        }

        /// <summary>
        /// 编辑工作经历页面
        /// </summary>
        [HttpGet]
        public ActionResult _EditUserWorkInfo(string spaceKey, long? workId)
        {
            User user = userService.GetFullUser(spaceKey);
            if (user == null)
                return HttpNotFound();

            WorkExperienceEditModel editModel = new WorkExperienceEditModel();

            int nowYear = DateTime.Now.Year;

            IList<string> startDateList = new List<string>();
            for (int i = 0; i <= 50; i++)
            {
                startDateList.Add((nowYear - i).ToString());
            }
            ViewData["StartDate"] = new SelectList(startDateList.Select(n => new { text = n.ToString(), value = n.ToString() }), "value", "text");

            IDictionary<string, string> endDateDict = new Dictionary<string, string>();

            endDateDict["至今"] = DateTime.Now.Year.ToString();
            for (int i = 1; i <= 50; i++)
            {
                endDateDict[(nowYear - i).ToString()] = (nowYear - i).ToString();
            }
            ViewData["EndDate"] = new SelectList(endDateDict.Select(n => new { text = n.Key, value = n.Value }), "value", "text");

            if (workId.HasValue && workId > 0)
            {
                WorkExperience edu = userProfileService.GetWorkExperience(workId.Value, user.UserId);
                if (edu != null)
                    editModel = edu.AsEditModel();
            }

            return View(editModel);
        }

        /// <summary>
        /// 编辑 工作经历
        /// </summary>
        /// <param name="model">用于表单提交的实体</param>
        [HttpPost]
        public JsonResult UpdateWork(string spaceKey, WorkExperienceEditModel model)
        {
            string message = string.Empty;
            if (ModelState.HasBannedWord(out message))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, message));
            }

            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            WorkExperience work = model.AsWorkExperience(userId);
            userProfileService.UpdateWorkExperience(work);
            if (work.Id > 0)
                return Json(new StatusMessageData(StatusMessageType.Success, "更新工作经历成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "更新工作经历失败!"));
        }

        /// <summary>
        /// 添加 工作经历表单提交
        /// </summary>
        /// <param name="model">用于表单提交的实体</param>
        [HttpPost]
        public JsonResult CreateWork(string spaceKey, WorkExperienceEditModel model,long userid)
        {
            string message = string.Empty;
            if (ModelState.HasBannedWord(out message))
            {
                return Json(new StatusMessageData(StatusMessageType.Error, message));
            }

            long userId = userid; //UserIdToUserNameDictionary.GetUserId(spaceKey);
            WorkExperience work = model.AsWorkExperience(userId);
            bool result = userProfileService.CreateWorkExperience(work);
            if (result)
                return Json(new StatusMessageData(StatusMessageType.Success, "创建工作经历成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "创建工作经历失败!"));
        }

        /// <summary>
        /// 删除工作经历
        /// </summary>
        /// <param name="WorkId">教育经历ID</param>
        [HttpPost]
        public JsonResult DeleteUserWork(string spaceKey, long WorkId)
        {
            userProfileService.DeleteWorkExperience(WorkId);
            if (WorkId > 0)
                return Json(new StatusMessageData(StatusMessageType.Success, "删除成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "删除失败!"));
        }

        #endregion 工作经历

        #region 个人标签

        /// <summary>
        /// 编辑用户资料-个人标签
        /// </summary>
        [HttpGet]
        public ActionResult EditUserTags(string spaceKey)
        {
            pageResourceManager.InsertTitlePart("个人标签");

            return View();
        }

        /// <summary>
        /// 编辑用户资料-用户个人标签控件
        /// </summary>
        [HttpGet]
        public ActionResult _ListMyUserTags(string spaceKey,long userid)
        {

            //OK

            long userId = userid; //UserIdToUserNameDictionary.GetUserId(spaceKey);

            TagService tagService = new TagService(TenantTypeIds.Instance().User());
            //取用户标签
            IEnumerable<ItemInTag> myUserTags = tagService.GetItemInTagsOfItem(userId);

            return View(myUserTags);
        }

        /// <summary>
        /// 编辑用户资料-所有用户标签
        /// </summary>
        [HttpGet]
        public ActionResult _ListUsersTags(string spaceKey,long userid)
        {
            //取所有用户标签
            TagService tagService = new TagService(TenantTypeIds.Instance().User());
            IDictionary<TagGroup, List<string>> tagsInGroupDict = new Dictionary<TagGroup, List<string>>();
            IEnumerable<TagGroup> tagGroups = tagService.GetGroups();
            if (tagGroups != null)
            {
                foreach (TagGroup tagGroup in tagGroups)
                {
                    tagsInGroupDict[tagGroup] = tagService.GetTopTagsOfGroup(tagGroup.GroupId, 20).ToList();
                }
            }

            int count = userProfileSettings.MaxPersonTag;
            if (tagGroups != null)
                ViewData["tagGroupsCount"] = tagGroups.ToList().Count;

            ViewData["count"] = count;
            return View(tagsInGroupDict);
        }

        /// <summary>
        /// 删除标签
        /// </summary>
        /// <param name="itemInTagId">标签关联ID</param>
        [HttpPost]
        public JsonResult DeleteMyUserTag(string spaceKey, long itemInTagId)
        {
            TagService tagService = new TagService(TenantTypeIds.Instance().User());
            tagService.DeleteTagFromItem(itemInTagId);
            if (itemInTagId > 0)
                return Json(new StatusMessageData(StatusMessageType.Success, "删除成功！"));
            else
                return Json(new StatusMessageData(StatusMessageType.Error, "删除失败!"));
        }

        private string TextFilter(string body, out bool isBanned)
        {
            isBanned = false;
            if (string.IsNullOrEmpty(body))
            {
                return body;
            }

            string temBody = body;
            WordFilterStatus staus = WordFilterStatus.Replace;
            temBody = WordFilter.SensitiveWordFilter.Filter(body, out staus);

            if (staus == WordFilterStatus.Banned)
            {
                isBanned = true;
                return body;
            }

            body = temBody;
            HtmlUtility.CleanHtml(body, TrustedHtmlLevel.Basic);

            return body;
        }

        /// <summary>
        /// 创建个人标签
        /// </summary>
        /// <param name="spaceKey">用户spaceKey</param>
        [HttpPost]
        public JsonResult CreateUserTag(string spaceKey)
        {
            bool isBanned = false;
            string tagName = Request.Form["TagName"];
            tagName = TextFilter(tagName, out isBanned);
            if (isBanned)
            {
                WebUtility.SetStatusCodeForError(Response);
                return Json(new StatusMessageData(StatusMessageType.Error, "内容中包含非法词语!"));
            }

            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            TagService tagService = new TagService(TenantTypeIds.Instance().User());

            int count = userProfileSettings.MaxPersonTag;
            if (tagService.GetItemInTagsOfItem(userId).Count() >= count)
            {
                WebUtility.SetStatusCodeForError(Response);
                return Json(new StatusMessageData(StatusMessageType.Error, "最多只能添加" + count + "个标签!"));
            }

            if (tagName != null)
            {
                tagService.AddTagToItem(tagName, userId, userId);
                return Json(new StatusMessageData(StatusMessageType.Success, "创建成功"));
            }
            WebUtility.SetStatusCodeForError(Response);

            return Json(new StatusMessageData(StatusMessageType.Error, "标签不能为空！"));
        }

        /// <summary>
        /// 创建关联个人标签
        /// </summary>
        /// <param name="spaceKey">用户spaceKey</param>
        public ActionResult AddTagToItem(string spaceKey, string tagName)
        {
            long userId = UserIdToUserNameDictionary.GetUserId(spaceKey);
            if (tagName != null)
            {
                TagService tagService = new TagService(TenantTypeIds.Instance().User());
                tagService.AddTagToItem(tagName, userId, userId);
            }

            return RedirectToAction("_ListMyUserTags", new { spaceKey = spaceKey, l = DateTime.UtcNow.Millisecond });
        }

        /// <summary>
        /// 管理我的标签，根据租户类型id查找
        /// </summary>
        /// <param name="spaceKey">用户spaceKey</param>
        /// <param name="tenantTypeId">租户类型id</param>
        /// <returns></returns>
        public ActionResult ManageMyTags(string spaceKey, string tenantTypeId)
        {
            //取所有用户标签
            TagService tagService = new TagService(tenantTypeId);
            IEnumerable<TagInOwner> tags = tagService.GetOwnerTags(UserContext.CurrentUser.UserId);

            pageResourceManager.InsertTitlePart("标签管理");

            return View(tags);
        }

        /// <summary>
        /// 创建标签页
        /// </summary>
        /// <returns></returns>
        public ActionResult _CreateMyTag(string spaceKey, string tenantTypeId)
        {
            TagEditModel tagEditModel = new TagEditModel();
            return View(tagEditModel);
        }

        /// <summary>
        /// 创建标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _CreateMyTag(string spaceKey, string tenantTypeId, TagEditModel tagEditModel)
        {
            IUser currentUser = UserContext.CurrentUser;
            if (currentUser != null && !string.IsNullOrEmpty(tagEditModel.TagName))
            {
                TagService tagService = new TagService(tenantTypeId);
                tagService.AddTagInOwner(tagEditModel.TagName, tenantTypeId, currentUser.UserId);
                return Json(new StatusMessageData(StatusMessageType.Success, "创建成功！"), JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "创建失败！"), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 删除我的标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _DeleteMyTags(string spaceKey, string tenantTypeId, IEnumerable<long> tagIds)
        {
            IUser currentUser = UserContext.CurrentUser;
            if (currentUser != null && tagIds.Count() > 0)
            {
                TagService tagService = new TagService(tenantTypeId);
                foreach (var tagId in tagIds)
                {
                    tagService.DeleteOwnerTag(tagId);
                }
                return Json(new { MessageType = StatusMessageType.Success, MessageContent = "删除成功！" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "删除失败！"), JsonRequestBehavior.AllowGet);
            }
        }

        /// <summary>
        /// 编辑我的标签
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult _EditMyTag(string spaceKey, TagEditModel tagEditModel, string tenantTypeId)
        {
            IUser currentUser = UserContext.CurrentUser;
            if (currentUser != null && tagEditModel.TagId > 0 && !string.IsNullOrEmpty(tagEditModel.TagName))
            {
                TagService tagService = new TagService(tenantTypeId);
                tagService.DeleteOwnerTag(tagEditModel.TagId);
                tagService.AddTagInOwner(tagEditModel.TagName, tenantTypeId, currentUser.UserId);
                return Json(new { MessageType = StatusMessageType.Success, MessageContent = "更新成功！" }, JsonRequestBehavior.AllowGet);
            }
            else
            {
                return Json(new StatusMessageData(StatusMessageType.Error, "更新失败！"), JsonRequestBehavior.AllowGet);
            }
        }
        /// <summary>
        /// 编辑我的标签页
        /// </summary>
        public ActionResult _EditMyTag(string spaceKey, long tagId, string tagName, string tenantTypeId)
        {
            TagEditModel tagEditModel = new TagEditModel();
            tagEditModel.TagId = tagId;
            tagEditModel.TagName = tagName;
            tagEditModel.TenantTypeId = tenantTypeId;
            return View(tagEditModel);
        }
        #endregion 个人标签

        #region 隐私私有方法

        /// <summary>
        /// 获取用户隐私设置
        /// </summary>
        /// <param name="userId">用户id</param>
        /// <param name="privacyItemKey">隐私设置标识</param>
        /// <param name="privacyStatus">默认状态</param>
        /// <returns>用户的默认设置</returns>
        private Dictionary<string, PrivacyStatus> GetUserPrivacySetting(long userId)
        {
            Dictionary<string, PrivacyStatus> userPrivacySettings = privacyService.GetUserPrivacySettings(userId);
            List<PrivacyItem> systemPrivacyItems = privacyService.GetPrivacyItems(null, null).ToList();
            Dictionary<string, PrivacyStatus> userPrivacySetting = new Dictionary<string, PrivacyStatus>();
            foreach (var item in systemPrivacyItems)
                userPrivacySetting[item.ItemKey] = userPrivacySettings.ContainsKey(item.ItemKey) ? userPrivacySettings[item.ItemKey] : item.PrivacyStatus;
            return userPrivacySetting;
        }

        /// <summary>
        /// 获取所有分组（我收藏的所有人）的实体
        /// </summary>
        /// <returns>所有分组（我收藏的所有人）的实体</returns>
        private UserPrivacySpecifyObject GetUserPrivacySpecifyObject_AllGroup()
        {
            UserPrivacySpecifyObject userPrivacySpecifyObject = UserPrivacySpecifyObject.New();

            userPrivacySpecifyObject.SpecifyObjectId = FollowSpecifyGroupIds.All;


            userPrivacySpecifyObject.SpecifyObjectName = "所有分组";
            userPrivacySpecifyObject.SpecifyObjectTypeId = SpecifyObjectTypeIds.Instance().UserGroup();
            return userPrivacySpecifyObject;
        }
        #endregion

    }
}